package com.cheer.security;

import cn.hutool.core.util.StrUtil;
import com.cheer.enums.CaptchaEnum;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author cheer
 */
public class ValidateCodeFilter extends OncePerRequestFilter {

    private AuthenticationFailureHandler authenticationFailureHandler;

    private final String pageUrl;

    private final String httpMethod;

    public ValidateCodeFilter(String pageUrl, String httpMethod) {
        this.pageUrl = pageUrl;
        this.httpMethod = httpMethod;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        if (new AntPathRequestMatcher(pageUrl, httpMethod).matches(request)) {
            HttpSession session = request.getSession();

            if (session.getAttribute(SecurityConfig.FAILED_LOGIN) != null) {
                Object object = session.getAttribute(CaptchaEnum.LOGIN.getAttribute());
                if (object == null) {
                    authenticationFailureHandler.onAuthenticationFailure(request, response,
                            new ValidateCodeException("请先获取验证码"));
                    return;
                }

                String code = (String) object;
                if (!StrUtil.equals(code, request.getParameter("code"))) {
                    session.removeAttribute(CaptchaEnum.LOGIN.getAttribute());
                    authenticationFailureHandler.onAuthenticationFailure(request, response,
                            new ValidateCodeException("验证码不正确"));
                    return;
                }
            }
        }

        filterChain.doFilter(request, response);
    }

    public ValidateCodeFilter setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
        this.authenticationFailureHandler = authenticationFailureHandler;
        return this;
    }
}